<script setup lang="ts">
import type { TableInstance } from 'element-plus'
import type { ColumnProps } from './types'
import { getCurrentInstance, provide, useSlots } from 'vue'
import TableColumn from './TableColumn.vue'

interface Props {
  columns: ColumnProps[] // 列配置
}

defineProps<Props>()

const slots = useSlots()

// 剥离 el-table 的 default、append和empty插槽，剩余的插槽就是el-table-column的插槽，全部注入到子组件中
const { default: defaultSlot, append: appendSlot, empty: emptySlot, ...otherSlots } = slots
provide('proTableSlots', otherSlots)

const vm = getCurrentInstance()!
/**
 * el-table 渲染完成后会回调此函数，把真实表格实例塞给我们
 * @param exposed  el-table 组件实例
 */
function changeRef(exposed: TableInstance) {
  // 将 el-table 组件实例挂载到当前组件实例上，方便外部通过ref获取到 el-table 实例
  vm.exposed = exposed
}
defineExpose({} as TableInstance)
</script>

<template>
  <el-table :ref="changeRef" v-bind="$attrs">
    <TableColumn v-for="col in columns" :key="col.prop || col.label" :column="col" />

    <template v-for="(_, slotName) in otherSlots" #[slotName]="slotProps" :key="slotName">
      <slot :name="slotName" v-bind="slotProps" />
    </template>
  </el-table>
</template>
